package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	_ "net/http/pprof"
	"os"
)

func main() {
	http.HandleFunc("/get", rootHandler)
	http.HandleFunc("/healthz", healthz)
	err := http.ListenAndServe(":80", nil)
	if err != nil {
		log.Fatal(err)
	}
}

// 4.当访问 localhost/healthz 时，应返回200
func healthz(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(200)
	io.WriteString(w, "ok\n")
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	// 获取中系统环境变量
	// 1.接收客户端 request，并将 request 中带的 header 写入 response header
	for k, v := range r.Header {
		arr1Byte, _ := json.Marshal(v)
		arr1Str := string(arr1Byte)
		w.Header().Set(k, arr1Str)
		io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
	}
	// 2.读取当前系统的环境变量中的 VERSION 配置，并写入 response header
	version := os.Getenv("VERSION")
	addrs, err := net.InterfaceAddrs()
	if err != nil {
	}
	arss := make([]string, 0)
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				arss = append(arss, ipnet.IP.String())
			}
		}
	}
	// 3.Server 端记录访问日志包括客户端 IP，HTTP 返回码，输出到 server 端的标准输出//
	code := 200
	fmt.Printf("客户端 {IP：%s,状态: %d} \n", r.RemoteAddr, code)
	// 设置请求头信息
	w.Header().Set("VERSION", version)
	// 设置状态码
	w.WriteHeader(200)
}
